import crypt
import os
from tornado import gen
from tornado import web

import sys
sys.path.append("..")

from utils.dbutil import MySQLConnection

class BaseHandler(web.RequestHandler):
    def get_current_user(self):
        user_info = self.get_secure_cookie("user_info")
        if user_info:
            arr = user_info.decode().split('-')
            user = {'accountid':arr[0], 'accountname':arr[1], 'truename':arr[2]}
            return user
            
        return None

# 首页
class MainHandler(BaseHandler):
    @web.authenticated
    @gen.coroutine
    def get(self):
        user = self.get_current_user()
        self.render('main.html', user=user)

# 登录
class LoginHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        self.clear_cookie("user_info")
        self.render('login.html', error=None)
    
    @gen.coroutine
    def post(self):
        username = self.get_argument("username")
        password = self.get_argument("password")
        conn = MySQLConnection.get_connection()
        try:
            with conn.cursor() as cursor:
                sql = "select accountid, accountname, truename from account where role=2 and \
                    accountname='{}' and password='{}'".format(username, password)
                print(sql)
                cursor.execute(sql)
                account = cursor.fetchone()
        finally:
            conn.close()
        print(account)
        if account:
            accountid = account['accountid']
            accountname = account['accountname']
            truename = account['truename']            
            self.set_secure_cookie("user_info", str(accountid) + "-" + accountname + "-" + truename)
            self.redirect("/")
        else:
            self.render('login.html', error='错误的用户名或密码')

class LogoutHandler(BaseHandler):
    @web.authenticated
    @gen.coroutine
    def get(self):
        self.clear_cookie("user_info")
        self.redirect('/login')

class ContactHandler(BaseHandler):
    @web.authenticated
    @gen.coroutine
    def get(self):
        self.render('contact.html', user=self.get_current_user())

default_handlers = [
    (r'/', MainHandler),
    (r'/login', LoginHandler),
    (r'/logout', LogoutHandler),
    (r'/contact', ContactHandler)
]